package com.d404.server;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.alibaba.fastjson.JSON;

import guanqu.server.DownloadInfo;
import im.beans.Classify;
import im.beans.User;
import im.notify.server.Notify;
import manager.DefaultSessionManager;
import manager.MessageManager;
import manager.PersistentManager;

/**
 * Servlet implementation class RemoveFriend
 */
// @WebServlet("/RemoveFriend")
public class RemoveFriend extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public RemoveFriend() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// response.getWriter().append("Served at:
		// ").append(request.getContextPath());

		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");

		SessionFactory sf = PersistentManager.sharemanager().getSessionFactory();
//		Session session = sf.openSession();
		Session session = sf.getCurrentSession();
		Transaction tx = session.beginTransaction();

		Upload upload = null;
		Download download = new Download();
		// 删除用户账号
		String rm_account = "";
		// 被删除用户账号
		String be_rm_account = "";

		try {
			String data = request.getParameter("data");
			upload = JSON.parseObject(data, Upload.class);
			User fromUser = new User();
			fromUser = (User) session.get(User.class, Long.parseLong(upload.getFromId().trim()));
			rm_account = fromUser.getAccount().trim();
			User toUser = new User();
			toUser = (User) session.get(User.class, Long.parseLong(upload.getUserId().trim()));
			be_rm_account = toUser.getAccount().trim();
			
			String userId = upload.getUserId();

			// 根据用户id获取其所在分组id

			Query qClassify = session.createQuery("from Classify c where c.ower = ?");

			qClassify.setParameter(0, fromUser);
			// qClassify.setMaxResults(1);

			for (Classify csf : (List<Classify>) qClassify.list()) {
				Classify classify = csf;

				// 根据分组id和被删除用户id，删除记录

				Query q = session.createQuery("delete from Classify_User cu where cu.user = ? and cu.classify = ?");

				q.setParameter(0, toUser);
				q.setParameter(1, classify);
				q.executeUpdate();
			}

			// 根据用户id获取其所在分组id

			Query qClassify1 = session.createQuery("from Classify c where c.ower = ?");

			qClassify1.setParameter(0, toUser);
			// qClassify1.setMaxResults(1);

			for (Classify csf : (List<Classify>) qClassify1.list()) {
				Classify classify1 = csf;

				// 根据分组id和被删除用户id，删除记录

				Query q1 = session.createQuery("delete from Classify_User cu where cu.user = ? and cu.classify = ?");

				q1.setParameter(0, fromUser);
				q1.setParameter(1, classify1);
				q1.executeUpdate();
			}

			tx.commit();
			// 通知被删除用户自己被好友删除
			Notify.BeRemoved beRemoved = new Notify.BeRemoved();
			beRemoved.setAccount(rm_account);
			MessageManager.sendSimpleMessage(be_rm_account, JSON.toJSONString(beRemoved));
			
			download.setStatus(DownloadInfo.SUCCESS);
		} catch (Exception e) {

			download.setStatus(DownloadInfo.FAILED);
			tx.rollback();
			e.printStackTrace();
		} finally {
//			session.close();

			response.getWriter().append(JSON.toJSONString(download));
		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

	// 上行数据
	public static class Upload {
		// 被删除者
		String userId;

		// 删除者
		String fromId;

		public String getUserId() {
			return userId;
		}

		public void setUserId(String userId) {
			this.userId = userId;
		}

		public String getFromId() {
			return fromId;
		}

		public void setFromId(String fromId) {
			this.fromId = fromId;
		}

	}

	// 下行数据
	public static class Download {
		int status;

		public int getStatus() {
			return status;
		}

		public void setStatus(int status) {
			this.status = status;
		}

	}
}
